package io.longpolling.test.controller;

import io.longpolling.support.AsyncResponseTask;
import io.longpolling.support.RequestParam;
import io.longpolling.support.TimeoutResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collection;

/**
 * 对外资源接口.
 */
@RestController
@RequestMapping("/resource")
@Slf4j
public class ResourceController {

    private static final String RESOURCE_SAY_HELLO = "SayHello";

    @GetMapping("/waitSayHello")
    public void waitSayHello(HttpServletRequest request, HttpServletResponse response, String who, Integer timeout) {

        //请求基础信息
        RequestParam curRequestParam = RequestParam.newInstance(RESOURCE_SAY_HELLO, who);
        //响应超时设置及返回结果
        TimeoutResult timeoutResult = TimeoutResult.newInstance(timeout, "Resp Timeout, but hello world for you!", HttpStatus.REQUEST_TIMEOUT);

        //开启异步响应
        AsyncResponseTask.buildAndStart(request, response, curRequestParam, timeoutResult);
        log.debug("<---wait say hello for {}!", who);
    }


    @PutMapping("/sayHello")
    public String sayHelloForWe() {
        final Collection<AsyncResponseTask> sayHelloRespTaskWaitList = AsyncResponseTask.getAsyncTask(RESOURCE_SAY_HELLO);
        final int total = sayHelloRespTaskWaitList.size();

        sayHelloRespTaskWaitList.forEach(asyncResp -> {
            RequestParam requestParam = asyncResp.getRequestParam();
            String who = (String) requestParam.getParam();

            String result = String.format("Hello %s!", who);
            asyncResp.returnJsonResult(result, HttpStatus.OK); //完成异步响应

            log.debug("--->say hello for {} success!", who);
        });

        return String.format("say hello for %s people!", total);
    }

}
